package com.sskj.gocoin;

import android.content.Context;
import android.util.SparseArray;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;

import java.util.List;

import androidx.annotation.LayoutRes;

/**
 * Created by Administrator on 2018/5/16.
 */

public abstract class MySpinnerAdapter<T> extends BaseAdapter {
    List<T> mData;
    Context mContext;
    int mLayoutId;

    public MySpinnerAdapter(Context context, List<T> mData, @LayoutRes int layoutId) {
        this.mData = mData;
        this.mContext = context;
        this.mLayoutId = layoutId;
    }

    @Override
    public int getCount() {
        return mData == null ? 0 : mData.size();
    }

    @Override
    public T getItem(int position) {
        return mData.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder = null;
        if (convertView == null) {
            convertView = View.inflate(mContext, mLayoutId, null);
            holder = new ViewHolder(convertView);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        bindView(holder, position, mData.get(position));
        return convertView;
    }

    public abstract void bindView(ViewHolder viewHolder, int position, T item);


    protected static class ViewHolder {
        View convertView;
        private final SparseArray<View> views;

        public ViewHolder(View view) {
            this.convertView = view;
            views = new SparseArray<>();
        }

        public <T extends View> T getView(int id) {
            View view = views.get(id);
            if (view == null) {
                view = convertView.findViewById(id);
                views.put(id, view);
            }
            return (T) view;
        }

    }

}


